from ..base import base
from flask import Flask, request, Response
import os
from http import HTTPStatus
import hashlib  # 新增导入
from dashscope import Application
from werkzeug.utils import secure_filename
from flask_cors import CORS
import PyPDF2
import docx
import openpyxl
from  .analysis import StandardInspect
from .analysis import DocumentInspection  # 在顶部导入
# from config import allowed_file
from .. import setup_logger  # 新增导入



logger = setup_logger(__name__)  # 新增日志初始化

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
# 修改ALLOWED_EXTENSIONS配置
app.config['ALLOWED_EXTENSIONS'] = {'doc', 'docx', 'pdf','xlsx'}

@base.route('/smart/check/upload', methods=['POST'])
def check_upload_file():
    if 'file' not in request.files:
        return {'error': '未选择文件'}, 400
    
    file = request.files['file']
    if file.filename == '':
        return {'error': '未选择文件'}, 400
    
    if file and allowed_file(file.filename):
        filename = file.filename.strip()
        # 添加文件名有效性检查
        if not filename or '.' not in filename:
            return {'error': '无效的文件名'}, 400
            
        # 确保上传目录存在
        upload_dir = app.config['UPLOAD_FOLDER']
        os.makedirs(upload_dir, exist_ok=True)  # 新增目录创建
        
        filepath = os.path.join(upload_dir, filename)
        try:
            file.save(filepath)
            logger.info(f"成功接收文件: {filename}")
            
            if filename.endswith(('.doc', '.docx')):
                parse_result = DocumentInspection.read_docx_tables(filepath)
                logger.info(f"成功解析Word文档: {filename} [大小: {os.path.getsize(filepath)}字节]")
                
                # 新增问题统计字段
                problem_count = 0
                if isinstance(parse_result, dict) and 'sections' in parse_result:
                    problem_count = sum(len(section.get('tables', [])) for section in parse_result['sections'])
                
                return {
                    'status': 'success',
                    'filename': filename,
                    'parse_result': parse_result,
                    'problem_count': problem_count,  # 新增问题数量字段
                    'file_size': os.path.getsize(filepath),
                    'checksum': hashlib.md5(open(filepath,'rb').read()).hexdigest()
                }
            else:
                return {'status': 'success', 'filename': filename}
                
        except Exception as e:
            logger.error(f"文件处理失败: {str(e)}", exc_info=True)
            return {
                'error': f'文件处理失败：{str(e)}',
                'error_type': type(e).__name__,
                'failed_step': 'file_processing'
            }
        return {'status': 'success', 'filename': filename}
        
        # 调用百炼API分析文档
    #     response = Application.call(
    #         api_key='sk-10ae285b266e4559922f610166717db1',
    #         app_id='6ef0ad19a3a04302b7eeb1082e1784c8',
    #         prompt=f"分析文档内容：{filepath}",
    #         session_id=app.session_id)
    #
    #     if response.status_code == HTTPStatus.OK:
    #         return {'status': 'success', 'analysis': response.output.text}
    #     else:
    #         return {'error': f"文档分析失败：{response.message}"}, 500
    # else:
    #     return {'error': '文件类型不支持'}, 400

if __name__ == '__main__':
    app.run(debug=True, port=5000)